package com.shenzhen.horselive.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.flqy.baselibrary.utils.GlideHelper;
import com.google.android.material.tabs.TabLayout;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.adapter.CityPartnerAdapter;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.AppBarActivity;
import com.shenzhen.horselive.beans.AuctionDetailsHeadBean;
import com.shenzhen.horselive.beans.CityMasterBaseBean;
import com.shenzhen.horselive.beans.ProfitRankingBean;
import com.shenzhen.horselive.beans.TeQuanBean;
import com.shenzhen.horselive.databinding.ActivityMyCityLordBinding;
import com.shenzhen.horselive.databinding.HeadCityLordBinding;
import com.shenzhen.horselive.databinding.HeadCityPartnerBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.presenter.ViewObserver;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 我的城主
 */
public class MyCityLordActivity extends AppBarActivity {

    ActivityMyCityLordBinding  binding;
    CityPickerView mPicker=new CityPickerView();
    private   int  type;
    private  String  code;
    private String  city;
    private  String  area;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding =ActivityMyCityLordBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        mPicker.init(this);
        areaCode = getIntent().getStringExtra("code");
        setStyleRed();
        setTitle("我的城主");
        setMenuText("竞拍大厅");
        initViews();
        initData();
    }
    String  areaCode;
    private void initData() {
        if (areaCode==null)
            return;
        //城主权益
        ApiFactory.getApiService().tequan(User.get().getMyInfo().getToken())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<TeQuanBean>(this) {
                    @Override
                    protected void onNextInActive(TeQuanBean cityMasterBaseBean) {
                        //百分比相关的字段介绍
                        if (cityMasterBaseBean.isSuccess())
                        {
                            headbinding.tvFeeText.setText("获得城市内所有会员领红包总额的"+cityMasterBaseBean.getData().getGetRatio()+"%");
                            headbinding.tvFeeText1.setText("获得城市内所有话费充值金额的"+cityMasterBaseBean.getData().getUserPhoneBillRatio()+"%");
                            headbinding.tvFeeText2.setText("获得城市内开卡奖励总额的"+cityMasterBaseBean.getData().getIncreasedFzRatio()+"%");
                            headbinding.tvFeeText3.setText("获得城市内矿主收益的"+cityMasterBaseBean.getData().getMinersProfitRatio()+"%");
                            headbinding.tvFeeText4.setText("获得城市内兑换矿证/兑换金卡总额的"+cityMasterBaseBean.getData().getUserConvertGoldCardRatio()+"%");
                            headbinding.tvFeeText5.setText("获得城市内支付公排/收钱吧收益总额的"+cityMasterBaseBean.getData().getUserPosRatio()+"%");
                            headbinding.tvFeeText6.setText("市级城主收益中包涵区，县城主收益的"+cityMasterBaseBean.getData().getAreaInCityRatio()+"%");

//                            headbinding.tvFeeText.setText("市级城主领红包股返佣比例"+cityMasterBaseBean.getData().getCityGetRatio()+"%");
//                            headbinding.tvFeeText1.setText("区县城主领红包股返佣比例"+cityMasterBaseBean.getData().getAreaGetRatio()+"%");
//                            headbinding.tvFeeText2.setText("用户充话费的抽成比率"+cityMasterBaseBean.getData().getUserPhoneBillRatio()+"%");
//                            headbinding.tvFeeText3.setText("新增峰值的抽成比率"+cityMasterBaseBean.getData().getIncreasedFzRatio()+"%");
//                            headbinding.tvFeeText4.setText("矿主收益的抽成比率"+cityMasterBaseBean.getData().getMinersProfitRatio()+"%");
//                            headbinding.tvFeeText5.setText("用户兑换矿证/金卡的抽成比率"+cityMasterBaseBean.getData().getUserConvertGoldCardRatio()+"%");
//                            headbinding.tvFeeText6.setText("公排用户奖励的抽成比率"+cityMasterBaseBean.getData().getUserPosRatio()+"%");


                        }
                    }
                });

        //选中的城市的基本信息和状态基本信息
//        ApiFactory.getApiService().findCityMasterBase(User.get().getMyInfo().getToken()
//        ,code).compose(SchedulersCompat.applyIoSchedulers())
//        .safeSubscribe(new ViewObserver<CityMasterBaseBean>(this) {
//            @Override
//            protected void onNextInActive(CityMasterBaseBean cityMasterBaseBean) {
//                if (cityMasterBaseBean.isSuccess())
//                {
//                    if (cityMasterBaseBean.getData()!=null)
//                    {
//                       type =  cityMasterBaseBean.getData().getStatus();
////                        0.待开放，1.第一次竞价中，2.第二次竞价中3.已锁定）
//                       switch (type)
//                       {
//                           case 0:
//                           case 3:
//                               //待开放或者已经锁定
//                               if (headbinding!=null)
//                               {
//                                   if (type==0)
//                                   {
//                                       headbinding.imgHead.setVisibility(View.GONE);
//                                       headbinding.containerCityMasterInfo.setVisibility(View.GONE);
//                                       headbinding.containerWaitOpen.setVisibility(View.VISIBLE);
//                                       headbinding.tvAreaName.setText(city+area);
//                                   }else
//                                   {
//                                       headbinding.imgHead.setVisibility(View.VISIBLE);
//                                       headbinding.containerCityMasterInfo.setVisibility(View.VISIBLE);
//                                       headbinding.containerWaitOpen.setVisibility(View.GONE);
//                                       //基本信息
//                                       headbinding.tvCity.setText("城市："+city+area);
//                                       GlideHelper.loadAdvertImage(cityMasterBaseBean.getData().getHeadImg(),headbinding.imgCityUserHead);
//                                       headbinding.tvNowMasterName.setText("城主："+cityMasterBaseBean.getData().getUserName());
////                                       headbinding.tvPrice.setText("¥"+cityMasterBaseBean.getData().getPrice());
////                                       headbinding.tvProfit.setText("¥"+cityMasterBaseBean.getData().getTotalProfit());
////                                       headbinding.tvNextSaleTime.setText(cityMasterBaseBean.getData().getExpirationTime());
//                                   }
////                                   //百分比相关的字段介绍
////                                   headbinding.tvFeeText.setText("即时享有主城内用户领取红包股总额的"+cityMasterBaseBean.getData().getCITY_GET_RATIO()+"%");
////                                   headbinding.tvFeeText1.setText("即时享有主城内用户充话费总额的"+cityMasterBaseBean.getData().getUSER_RED_ENVELOPERS_SHARES_RATIO()+"%");
////                                   headbinding.tvFeeText2.setText("即时享有主城内新增蜂值总额的"+cityMasterBaseBean.getData().getUSER_PHONE_BILL_RATIO()+"%");
////                                   headbinding.tvFeeText3.setText("即时享有主城内所有矿主总收益的"+cityMasterBaseBean.getData().getINCREASED_FZ_RATIO()+"%");
////                                   headbinding.tvFeeText4.setText("即时享有主城内用户兑换矿证"+cityMasterBaseBean.getData().getMINERS_PROFIT_RATIO()+"%");
////                                   headbinding.tvFeeText5.setText("即时享有主城内POS公排用户奖励的"+cityMasterBaseBean.getData().getUSER_CONVERT_GOLD_CARD_RATIO()+"%");
////                                   headbinding.tvFeeText6.setText(String.format("备注：若市级城主范围产生了区县级城主，分配比例为：市级s%%，区县s%%",cityMasterBaseBean.getData().getCITY_GET_RATIO(),cityMasterBaseBean.getData().getAREA_GET_RATIO()));
//
//                               }
//                               break;
//                           case 2:
//                               //竞价中
//                              //跳转到竞价中的页面
//                               MyCityLordAuctioningActivity.start(MyCityLordActivity.this,code);
//                               finish();
//                               break;
//                       }
//
//                    }
//
//                }else
//                {
//                    showToast(cityMasterBaseBean.getErrMessage());
//                }
//            }
//        });

        //头部信息获取
        ApiFactory.getApiService().auctionHeadDetails(User.get().getMyInfo().getToken()
        ,areaCode).compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<AuctionDetailsHeadBean>(this) {
                    @Override
                    protected void onNextInActive(AuctionDetailsHeadBean auctionDetailsHeadBean) {
                        if (auctionDetailsHeadBean.isSuccess())
                        {
//                            城市的状态 0待开放 1第一次竞价中 2第二次竞价中 3流拍中 4已锁定 （1,2,3状态都为竞拍中）
                            int  statues =  auctionDetailsHeadBean.getData().getStatus();
                            switch (statues)
                            {
                                case 0:
                                    headbinding.imgHead.setVisibility(View.GONE);
                                    headbinding.containerCityMasterInfo.setVisibility(View.GONE);
                                    headbinding.containerWaitOpen.setVisibility(View.VISIBLE);
                                    //地名
                                    headbinding.tvAreaName.setText(auctionDetailsHeadBean.getData().getAreaName());

                                    binding.btGo.setText("该城暂不出售");
                                    binding.btGo.setTextColor(getResources().getColor(R.color.color_6));
                                    binding.btGo.setEnabled(false);

                                    break;
                                case 4:
                                    //已经锁定
                                    headbinding.imgHead.setVisibility(View.VISIBLE);
                                    headbinding.containerCityMasterInfo.setVisibility(View.VISIBLE);
                                    headbinding.containerWaitOpen.setVisibility(View.GONE);
                                    //设置基本的信息
                                    headbinding.tvCity.setText("城市："+auctionDetailsHeadBean.getData().getAreaName());
                                   GlideHelper.loadAdvertImage(auctionDetailsHeadBean.getData().getHeadImg(),headbinding.imgCityUserHead);
                                   headbinding.tvNowMasterName.setText(auctionDetailsHeadBean.getData().getUserName());
                                   headbinding.tvState.setText("城市状态：已锁定");
                                   headbinding.tvPrice.setText(formatNum(auctionDetailsHeadBean.getData().getPrice())+"(蜂值)");
                                   headbinding.tvProfit.setText(formatNum(auctionDetailsHeadBean.getData().getProfit())+"(蜂值)");
                                   headbinding.tvNextSaleTime.setText(auctionDetailsHeadBean.getData().getNextAuctionTime());

                                    binding.btGo.setText("该城暂不出售");
                                    binding.btGo.setTextColor(getResources().getColor(R.color.color_6));
                                    binding.btGo.setEnabled(false);
                                    break;
                                case 1:
                                case 2:
                                case 3:
                                    //竞拍中，直接跳转另外的页面
                                    AuctionDetailsActivity.start(getContext(),areaCode,1);
                                    finish();
                                    break;
                            }

                        }
                    }
                });

        //城市收益排行
        getProfitRanking();
    }

    //城市收益排行榜
    private void getProfitRanking() {

        ApiFactory.getApiService().profitRankingList(User.get().getMyInfo().getToken())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<ProfitRankingBean>(this) {
                    @Override
                    protected void onNextInActive(ProfitRankingBean profitRankingBean) {
                        if (profitRankingBean.isSuccess())
                        {
                            adapter.setNewData(profitRankingBean.getData());

                        }else
                        {
                            showToast(profitRankingBean.getErrMessage());
                        }
                    }
                });
    }

    //城市价格排行榜
    private  void   getPriceRankingList()
    {
        ApiFactory.getApiService().priceRankingList(User.get().getMyInfo().getToken())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<ProfitRankingBean>(this) {
                    @Override
                    protected void onNextInActive(ProfitRankingBean profitRankingBean) {
                        if (profitRankingBean.isSuccess())
                        {
                            adapter.setNewData(profitRankingBean.getData());

                        }else
                        {
                            showToast(profitRankingBean.getErrMessage());
                        }
                    }
                });
    }



    CityPartnerAdapter adapter;
    private void initViews() {
//        （0.待开放，1.第一次竞价中，2.第二次竞价中3.已锁定
        type =getIntent().getIntExtra("type",0);
        code = getIntent().getStringExtra("code");
        city =getIntent().getStringExtra("city");
        area =getIntent().getStringExtra("area");
        binding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
        adapter =new CityPartnerAdapter(R.layout.item_citypater);
        binding.recyclerview.setAdapter(adapter);
        adapter.addHeaderView(initHead());
        binding.btGo.setOnClickListener(onClickListener);
        binding.btCity.setOnClickListener(onClickListener);




    }

    long  lasttime;
    private View.OnClickListener  onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            long nowtime =  System.currentTimeMillis();
            if ((nowtime-lasttime)/1000<1)
            {
                return;
            }
            lasttime=  nowtime;
            switch (v.getId())
            {
                case R.id.bt_go:
//                    startActivity(new Intent(MyCityLordActivity.this,PayAuctionCityActivity.class));
                    break;
                case R.id.bt_city:
                    openCityPick();
                    break;
            }

        }
    };

    HeadCityLordBinding headbinding;
    //初始化头部
    private View initHead() {
         headbinding = HeadCityLordBinding.inflate(getLayoutInflater());
         headbinding.tabs.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
             @Override
             public void onTabSelected(TabLayout.Tab tab) {
                 switch (tab.getPosition())
                 {
                     case 0:
                         getProfitRanking();
                         break;
                     case 1:
                         getPriceRankingList();
                         break;
                 }
             }

             @Override
             public void onTabUnselected(TabLayout.Tab tab) {

             }

             @Override
             public void onTabReselected(TabLayout.Tab tab) {

             }
         });

        return headbinding.getRoot();
    }

    @Override
    protected void onActionMenuViewClick() {
        super.onActionMenuViewClick();
        startActivity(new Intent(this,AuctionHallActivity.class));
    }

    //打开城市选择器
    private void openCityPick() {
//        AreaPicker areaPicker = new AreaPicker();
//        areaPicker.setListener(new AreaPicker.AreaPickerListener() {
//            @Override
//            public void onPicked(String province, String city) {
//                binding.tvChooseCity.setText(province+""+city);
//            }
//        });
//        areaPicker.show(getSupportFragmentManager());

        //监听选择点击事件及返回结果
        //添加默认的配置，不需要自己定义，当然也可以自定义相关熟悉，详细属性请看demo
        CityConfig cityConfig = new CityConfig.Builder()
                .cityCyclic(false)
                .provinceCyclic(false)
                .districtCyclic(false)
                .build();
        mPicker.setConfig(cityConfig);
        mPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {

                //更新数据
                areaCode =district.getId();
                initData();

            }
            @Override
            public void onCancel() {

            }
        });

        //显示
        mPicker.showCityPicker( );
    }


    public static void start(Context context,String  areacode) {
        Intent starter = new Intent(context, MyCityLordActivity.class);
        starter.putExtra("code",areacode);
        context.startActivity(starter);
    }


    private  String  formatNum(String  num)
    {
        if (num!=null)
        {
            NumberFormat format = NumberFormat.getInstance();
            format.setMaximumFractionDigits(10);
            return format.format(Double.parseDouble(num));
        }
        else
        {
            return null;
        }
    }

}